package com.atguigu.guli.infrastructure.apigateway.filter;

import com.atguigu.guli.service.base.helper.JwtHelper;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取浏览器发起的请求
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        if (!pathMatcher.match("api/**/auth/**",path)){
            //不匹配直接放行
            return chain.filter(exchange);
        }
        //如果匹配则确认请求头中是否携带token参数
        String token = request.getHeaders().getFirst("token");
        boolean flag = JwtHelper.checkToken(token);
        if (flag) {
            //鉴权成功，直接放行
            return chain.filter(exchange);
        }
        //封装响应体内容，返回响应给浏览器
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("code", ResultCodeEnum.LOGIN_AUTH.getCode());
        jsonObject.addProperty("success",ResultCodeEnum.LOGIN_AUTH.getSuccess());
        jsonObject.addProperty("message","网关鉴权失败的响应");
        String json = jsonObject.toString();
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer wrap = response.bufferFactory().wrap(json.getBytes());
        response.getHeaders().add("Content-type","application/json;charset=UTF-8");
        return response.writeWith(Mono.just(wrap));
    }

    //设置拦截器的优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
